package main

import (
	"net/http"
	"net/http/httputil"
	"net/url"
)

type baseHandle struct{}

func (h *baseHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var (
		hostTarget = map[string]string{
			"passport.beesoft.com": "http://localhost:8081",
			"payment.beesoft.com":  "http://localhost:8082",
			"message.beesoft.com":  "http://localhost:8883",
		}
		hostProxy = map[string]*httputil.ReverseProxy{}
	)

	host := r.Host

	if fn, ok := hostProxy[host]; ok {
		fn.ServeHTTP(w, r)

		return
	}

	if target, ok := hostTarget[host]; ok {
		remoteUrl, err := url.Parse(target)
		if err != nil {
			panic(err)
		}

		proxy := httputil.NewSingleHostReverseProxy(remoteUrl)
		hostProxy[host] = proxy
		proxy.ServeHTTP(w, r)

		return
	}

	_, err := w.Write([]byte("403: Host forbidden " + host))
	if err != nil {
		panic(err)
	}
}
